package org.example.sunrise.views;

import javafx.animation.AnimationTimer;
import javafx.application.Platform;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.BorderPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import org.example.sunrise.core.Context;
import org.example.sunrise.views.models.SimpleGameViewModel;

import java.util.Objects;

public class SimpleGameView extends BorderPane {
    private final Context ctx;
    private final SimpleGameViewModel viewModel = new SimpleGameViewModel();

    public SimpleGameView(Context ctx) {
        this.ctx = ctx;
        createView();
    }

    private void createView() {
        MediaPlayer mediaPlayer = createMusic();
        Canvas canvas = new Canvas(ctx.width(), ctx.height());
        GraphicsContext gc = canvas.getGraphicsContext2D();
        this.setCenter(canvas);
        ctx.stage().setOnCloseRequest(viewModel::stopTask);
        canvas.setOnMouseClicked(viewModel::onMouseClicked);
        canvas.setOnMouseMoved(viewModel::onMouseMoved);
        Platform.runLater(() -> {
            new AnimationTimer() {
                @Override
                public void handle(long l) {
                    viewModel.render(gc);
                    mediaPlayer.play();
                }
            }.start();
            viewModel.runTask();
        });
    }

    private MediaPlayer createMusic() {
        Media media = new Media(Objects.requireNonNull(SimpleGameView.class.getResource("defaultGame/music/game.mp3")).toString());
        MediaPlayer mediaPlayer = new MediaPlayer(media);
        mediaPlayer.setOnEndOfMedia(() -> mediaPlayer.seek(mediaPlayer.getStartTime()));
        return mediaPlayer;
    }
}
